package com.pralo.barcodeinfo;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.droidsoapclient.client.SoapClient;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.serialization.PropertyInfo;

import android.util.Log;

public class DataExchangeControler {

	private static String NAMESPACE = "urn:services-progress-com:wsa-admin:02:qadItem";
	private static String URL = "http://10.1.4.8:8080/wsa/wsa1";
	private static String SOAP_ACTION = "";
	private static String METHOD_NAME = "getItemInfo";
	public static Item resultItems = new Item();

	// initialization of SOAP connection parameters
	public static void initURL(String host) {

		NAMESPACE = "urn:services-progress-com:wsa-admin:02:qadItem";
		URL =  host ;
		SOAP_ACTION = "";
		METHOD_NAME = "getItemInfo";
	}


	// Ckeck connection function
	public static String checkConnection() {
		String res = "";
		SoapObject request = new SoapObject(NAMESPACE, "checkConnection");
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,5000);
		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
			res = resultsRequestSOAP.toString();
			res = extractResult("checkConnection", res);
		} catch (Exception e) {
			res = e.getMessage();
			System.out.println("Error" + e);
		}
		
		return res;
	}


	public static String checkUser(String user, String pass) {
		String res = "";
		SoapObject request = new SoapObject(NAMESPACE, "userValidation");
		request.addProperty("inID", user);
		request.addProperty("inPASS", pass);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,5000);
		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
			res = resultsRequestSOAP.toString();
		} catch (Exception e) {
			res = e.getMessage();
			System.out.println("Error" + e);
		}
		if (res.contains("true")) {
			res = "true";
		} else if ((res.contains("timed out")) || (res.contains("failed"))){
			res = "timedout";
		} else {
			res = "false";
		}
		return res;
	}

	// sample 
//	public static String getBarcodeInfo(String barcode) {
//		String res = "";
//
//		ReportClass RC = new ReportClass();
//		RC.Barcode = "2";
//
//		SoapObject request = new SoapObject(NAMESPACE, "getBarcodeData");
//		request.addProperty("arg0", RC);
//		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
//				SoapEnvelope.VER11);
//		envelope.setOutputSoapObject(request);
//		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,10000);
//
//		try {
//			androidHttpTransport.call(SOAP_ACTION, envelope);
//			SoapObject response = (SoapObject) envelope.getResponse();
//			RC.Barcode = response.getProperty(0).toString();
//			RC.Description = response.getProperty(1).toString();
//			RC.ProductLine = response.getProperty(2).toString();
//			res = "Barcode: " + RC.Barcode + "/ Description: " + RC.Description
//					+ "/ ProductLine: " + RC.ProductLine;
//		} catch (Exception e) {
//			res = e.getMessage();
//			System.out.println("Error" + e);
//		}
//
//		return res;
//	}

	public static String getItemInfo(String barcode) {
		String res = "";
		SoapObject request = new SoapObject(NAMESPACE, "getItemInfo");
		request.addProperty("inUser", LoginControler.userS);
		request.addProperty("inBarCode", barcode);
		request.addProperty("inDomain", "elmoris");

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = false;
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,10000);
		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapObject response = (SoapObject) envelope.bodyIn;
			res = extractResultItem(response.toString(),barcode);
		} catch (Exception e) {
			res = "Error:" + e.getMessage();
			System.out.println("Error" + e);
		}

		return res;
	}

	// extract SOAP result as string
	public static String extractResult(String functionName, String str) {
		String rez = str;
		try {
			rez = rez.substring(functionName.length() + 16, str.length() - 3);
		} catch (Exception ex) {
			rez = "";
		}
		return rez;
	}

	// extract SOAP result as string array
	public static String[] extractResultsArray(String functionName, String str) {
		String[] rezArray = new String[10];
		String rez = "";
		try {
			rez = str.substring(functionName.length() + 29, str.length() - 6);
			String[] parts = rez.split("; item=");
			rez = "";
			for (int i = 0; i < parts.length; i++) {
				rez = rez + parts[i] + "#";
				rezArray[i] = parts[i];
			}
		} catch (Exception ex) {
			rez = "";
		}
		return rezArray;
	}

	public static String extractResultItem(String str,String barcode) {
		String rez = "true";
		resultItems = new Item();
		dsItem dsin = new dsItem();
		ttItem ttitn = new ttItem();
		ttitn.item=barcode;
		ttitn.msg="";
		dsin.ttitem = ttitn;
		ttSerial tts = new ttSerial();
		List<ttSerial> tttsr = new ArrayList<ttSerial>();
		for (int y = 0; y < 3; y++) {
			tts.item = "-";
			tts.lot = "-";
			tts.ref = "-";
			tts.loc = "-";
			tts.qty = "-";
		}
		tttsr.add(tts);
		dsin.ttserial = tttsr;
		resultItems.ds = dsin;
		String resultsstring = "none";
		try {
			int ix1 = str.indexOf("; dsItem=");
			resultsstring = str.substring(27, ix1);
			rez = str.substring(68, str.length() - 9);
			rez = rez.replace("anyType{}", "none");
			String[] objects = new String[100];
			Pattern pattern = Pattern.compile(Pattern.quote("; }; "));
			objects = pattern.split(rez);
			dsItem dsi = new dsItem();
			ttItem ttit = new ttItem();
			List<ttSerial> ttsr = new ArrayList<ttSerial>();
			for (int i = 0; i < objects.length; i++) {
				if (i == 0) {
					String[] fields = objects[i].split("; ");
					for (int y = 0; y < fields.length; y++) {
						if (fields[y].contains("item="))
							ttit.item = fields[y].replace("item=", "");
						if (fields[y].contains("msg="))
							ttit.msg = fields[y].replace("msg=", "");
						if (fields[y].contains("domain="))
							ttit.domain = fields[y].replace("domain=", "");
						if (fields[y].contains("domain_name="))
							ttit.domain_name = fields[y].replace("domain_name=", "");
						if (fields[y].contains("um="))
							ttit.um = fields[y].replace("um=", "");
						if (fields[y].contains("desc1="))
							ttit.desc1 = fields[y].replace("desc1=", "");
						if (fields[y].contains("desc2="))
							ttit.desc2 = fields[y].replace("desc2=", "");
						if (fields[y].contains("prod_line="))
							ttit.prod_line = fields[y]
									.replace("prod_line=", "");
						if (fields[y].contains("part_type="))
							ttit.part_type = fields[y]
									.replace("part_type=", "");
						if (fields[y].contains("abc="))
							ttit.abc = fields[y].replace("abc=", "");
						if (fields[y].contains("ship_wt="))
							ttit.ship_wt = fields[y].replace("ship_wt=", "");
						if (fields[y].contains("net_wt=="))
							ttit.net_wt = fields[y].replace("net_wt=", "");
						if (fields[y].contains("supplier=="))
							ttit.supplier = fields[y].replace("supplier=", "");
						if (fields[y].contains("qty="))
							ttit.qty = fields[y].replace("qty=", "");
						if (fields[y].contains("serial_count="))
							ttit.serial_count = fields[y].replace(
									"serial_count=", "");
					}
				} else {
					String[] fields = objects[i].replace("tt-serial=anyType{",
							"").split("; ");
					ttSerial ts = new ttSerial();
					for (int y = 0; y < fields.length; y++) {
						if (fields[y].contains("item="))
							ts.item = fields[y].replace("item=", "");
						if (fields[y].contains("lot="))
							ts.lot = fields[y].replace("lot=", "");
						if (fields[y].contains("ref="))
							ts.ref = fields[y].replace("ref=", "");
						if (fields[y].contains("loc="))
							ts.loc = fields[y].replace("loc=", "");
						if (fields[y].contains("qty="))
							ts.qty = fields[y].replace("qty=", "");
					}
					ttsr.add(ts);
				}
			}
			dsi.ttitem = ttit;
			dsi.ttserial = ttsr;
			resultItems.ds = dsi;
			resultItems.result = resultsstring;
			rez = resultsstring;
		} catch (Exception ex) {
			rez = "false";
		}
		return rez;
	}

}
